package com.inspectortime.webapp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.User;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class LoginController extends SimpleFormController {

	private static Log log = LogFactory.getLog(LoginController.class);
	
	private Repository repository;

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new LoginForm();
	}

	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		LoginForm form = (LoginForm) command;
		ValidationUtils.rejectIfEmpty(errors, "userName", "required");
		ValidationUtils.rejectIfEmpty(errors, "password", "required");
		if (errors.getErrorCount() > 0) {
			return new ModelAndView(getFormView(), errors.getModel());
		}

		User user = repository.findUserByEmailOrUserName(form.getUserName());
		if (user == null) {
			errors.rejectValue("userName", "notFound", null, "User not found");
			return new ModelAndView(getFormView(), errors.getModel());
		}
		
		// Password match?
		if (!user.passwordMatches(form.getPassword())) {
			errors.rejectValue("userName", "notFound", null, "Invalid password");
			return new ModelAndView(getFormView(), errors.getModel());
		}
		
		// Stick user in session
		HttpSessionUtils.invalidateExistingSession(request);
		HttpSessionUtils.storeLoggedInUser(request, user);
		log.info("User logged in: " + user.getEmail());

		// render success view
		if (getSuccessView() == null) {
			throw new ServletException("successView isn't set");
		}
		return new ModelAndView(getSuccessView(), errors.getModel());
	}

}
